
# true if you want a "sorry no matches" comment
write.note=TRUE

MT = read.csv( "final_matches_done.csv", stringsAsFactors=FALSE )
MT$comments[ is.na( MT$comments ) ] = ""
MT$comments[ MT$comments == " " ] = ""
MT[is.na(MT)] = ""

## Format of MT is:
## personID pubname email comments ID, ID, ID, ID ...

## general idea--cruise through the list and mark true for any id 
## that is in the row of the owner id
## make a 2d matrix of boolean matches.  Do a transposition and and, 
## and look for remaining mutual
## matches.  Then prettify.


for( i in 6:ncol(MT) ) {
	MT[[i]] = toupper(MT[[i]])
}

N = length( MT[[1]] )
cols = length( MT )

mat = matrix( rep( FALSE, N^2 ), nrow=N )

## For each row, mark off any ids that are left in the matrix
for ( i in 1:N ) {
	mat[i,] = MT$personID %in% MT[i, 6:cols] 
}

m2 = mat & t(mat)
m2 = as.data.frame( m2 )
rownames(m2) = MT$personID
names( m2 ) = MT$personID

allL = list()


for ( i in 1:N ) {
	
	r = m2[[i]]
	#print( r )
	nms = MT$personID[r]
	rnms = MT$pubname[r]
	email = MT$email[r]
	#nms
	
	df = data.frame( name=rnms, ID=nms, email=email )
	df
	if ( length(df[[1]]) == 0 && write.note ) {
		df = "Sorry, no matches this time!"
	}
	
	allL[[ i ]] = df
	
}
names(allL) = MT$personID

# number of matches for folks
numm = sapply( allL, function(X) { length( X[[1]] ) } )
des = apply(mat,1,sum )
res = data.frame( got=numm, want=des )
res$diff = res$want - res$got
table( res$diff )


cat( "FINAL RESULTS\n\n", file="out.txt" )

for ( i in 1:N ) {
	
	#cat( "\n\n", MT$personID[[i]], "\n\n\n\n\n\n\n\n", MT$email[[i]], "\nDear ", MT$pubname[[i]], " ( #", MT$personID[[i]], "),\n\nYour matches are:\n",
	#	 file="out.txt", append=TRUE )
	
	cat( MT$email[[i]], "\n\nDear ", MT$pubname[[i]], " ( #", MT$personID[[i]], "),\n\nThank you so much for coming to the Poly Speed Dating event.  We hope you had a great time.  Your matches are:\n\n",
		 file="out.txt", append=TRUE )
	
	if ( class( allL[[i]] ) == "character" ) {
		cat( "\n    ", allL[[i]], "\n\n",
			 file="out.txt", append=TRUE )
		
	} else {
		write.csv( allL[[i]],
			 file="out.txt", append=TRUE, quote=FALSE )
		cat( "\nYour email, ", MT$email[[i]], ", has been sent to the above people.  ", sep="", file="out.txt", append=TRUE )
	}
	
	if ( MT$comments[[i]] != "" ) {
		cat( "\nExtra note: ", MT$comments[[i]], "\n", sep="",
			 file="out.txt", append=TRUE )
	}
	
	cat( "Please note that we found that we missed some matches from the handed-out forms.  Please check the above to see if you have more matches!  Also, if you still believe there is a mistake, please contact us so we can double check.  We have been known to miss matches, and that is a terrible thing!  It was wonderful having you at the event, and we hope to see you at future ones.\n\n\t- the poly speed dating team\n\f", sep="",
		 file="out.txt", append=TRUE )

}
	
	
